/*
 * Copyright 2010 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alertleon;

import static com.configleon.configurer.AbstractPropertyConfigurer.JVM_VARIABLE_NAME;

import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.CollectionUtils;

/*
 * The following configuration properties are required for this class:
 *
 * alert.fromAddr=error@mycompany.com
 * alert.port=25 (optional, defaults to "25")
 * alert.smtpServer=mail.mycompany.com
 * alert.subject=ErrorAlert-Local Content
 * alert.toAddr=your_email@mycompany.com
 */
public class EmailAlertListener implements AlertListener {

    private Log logger = LogFactory.getLog(EmailAlertListener.class);

    private final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    private AlertConfiguration configuration;

    public EmailAlertListener(AlertQueue queue) {
        this.configuration = queue.getConfiguration();

        javaMailSender.setPort(configuration.getPort());
        javaMailSender.setHost(configuration.getSmtpServer());
    }

    public void handleAlerts(Set<String> messages) {
        if (!CollectionUtils.isEmpty(messages)) {
            sendEmail(messages);
        }
    }

    private void sendEmail(Set<String> messages) {
        SimpleMailMessage email = buildEmail(messages);

        try {
            javaMailSender.send(email);
        } catch (Exception e) {
            logger.error("Error while sending the email message.", e);
        }
    }

    private SimpleMailMessage buildEmail(Set<String> messages) {
        SimpleMailMessage email = new SimpleMailMessage();

        String[] addresses = configuration.getToAddress().split(",");
        email.setTo(addresses);
        email.setFrom(configuration.getFromAddress());

        String subject = configuration.getSubject();
        String location = System.getProperty(JVM_VARIABLE_NAME);

        if (location != null) {
            subject += " (" + location + ")";
        }

        email.setSubject(subject);

        StringBuilder body = new StringBuilder();

        for (String message : messages) {
            body.append(message);
            body.append("\r");
            body.append("\r");
        }

        email.setText(body.toString());

        return email;
    }
}